import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import mail

import EventRecord
import RegistrationRecord

class EventBroadcast( webapp.RequestHandler ):

  def post( self ):
    self.response.headers['Content-Type'] = 'text/html'

    id = self.request.get('id')
    passcode = self.request.get('passcode')
    msg = self.request.get('msg')

    record = EventRecord.EventRecord \
      .gql( 'WHERE id=:1 AND passcode=:2', id, passcode ) \
      .get()
    if not record:
      self.response.out.write( 'Event not found!' )
      return
    sender = record.email

    guests = RegistrationRecord.RegistrationRecord \
      .gql( 'WHERE id = :1 ORDER BY email ASC', id )
    emails = []
    last_guest = None
    for guest in guests:
      if last_guest is None or guest.email != last_guest.email:
        emails.append( guest.email )
      last_guest = guest

    mail.send_mail(
      sender = sender,
      to = sender,
      bcc = emails,
      subject = "[Misc-App] Event Message Broadcast",
      body = '%s\r\n\r\n--\r\nMessage Broadcast by Misc-App Collection.\r\n' % msg )

    self.redirect( 'admin?id=%s&passcode=%s' % (id, passcode) )
  # end of EventBroadcast.post

# end of class EventBroadcast
